package com.ruoyi.common.core.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Slf4j
@Component
public class SendSmsUtil implements Serializable {
    @Value("${tencent.sms.secret-id}")
    private String secretId;

    @Value("${tencent.sms.secret-key}")
    private String secretKey;

    @Value("${tencent.sms.sdk-app-id}")
    private String sdkAppId;

    @Value("${tencent.sms.sign-name}")
    private String signName;

    @Value("${tencent.sms.login-template-id}")
    private String templateId;

    public void sendSmsCode(String phone, String msg) {
        try {
            // 实例化认证对象
            Credential cred = new Credential(secretId, secretKey);

            // 配置HTTP请求参数
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            httpProfile.setReqMethod("GET");
            httpProfile.setConnTimeout(10);
            httpProfile.setWriteTimeout(10);
            httpProfile.setReadTimeout(10);

            // 配置客户端参数
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);

            // 修复1：地域参数格式错误（"apguangzhou" → "ap-guangzhou"，中间有非法特殊字符）
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

            // 构建发送请求
            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppId(sdkAppId);
            req.setSignName(signName);
            req.setTemplateId(templateId);

            // 修复2：定义phoneNumberSet（按E.164标准拼接+86前缀）
            String[] phoneNumberSet = {"+86" + phone}; // 关键修复：将传入的手机号转为数组并添加国家码
            req.setPhoneNumberSet(phoneNumberSet);

            // 模板参数：1个参数（与你的模板{1}占位符匹配）
            String[] templateParamSet = {msg};
            req.setTemplateParamSet(templateParamSet);

            // 可选参数（保留默认空值）
            req.setSessionContext("");
            req.setExtendCode("");
            req.setSenderId("");

            // 发起请求并处理响应
            SendSmsResponse res = client.SendSms(req);
            String jsonResponse = SendSmsResponse.toJsonString(res);

            // 优化：区分成功/失败日志，避免误判
            boolean isSuccess = true;
            for (SendStatus status : res.getSendStatusSet()) {
                String formattedPhone = status.getPhoneNumber().replace("+86", ""); // 格式化手机号显示
                if ("Ok".equals(status.getCode())) {
                    log.info("【短信发送成功】手机号：{}，模板参数：{}，响应：{}", formattedPhone, msg, jsonResponse);
                } else {
                    isSuccess = false;
                    log.error("【短信发送失败】手机号：{}，错误码：{}，原因：{}，完整响应：{}",
                            formattedPhone, status.getCode(), status.getMessage(), jsonResponse);
                }
            }

            // 失败时抛出异常，便于业务层处理
            if (!isSuccess) {
                throw new RuntimeException("短信发送失败，请检查模板参数或配置");
            }

        } catch (TencentCloudSDKException e) {
            log.error("【短信发送异常】手机号：{}，原因：{}", phone, e.getMessage());
            throw new RuntimeException("短信发送失败，请稍后重试");
        }
    }
}